import asyncio
import base64
import math
from datetime import datetime, timedelta
from typing import List

import pydash
import urllib3

from dayu import Dayu
from tools.config import get_config
from tools.workdays import count_working_saturdays, get_workdays
from user import User

urllib3.disable_warnings()
# 获取当前日期
now = datetime.now()
deptId = 667742106  # 研发中心
quarter = f"{now.year}-Q{math.ceil(now.month / 3)}"  # 赛季
today = now.strftime("%Y-%m-%d")
lastday = (now - timedelta(days=1)).strftime("%Y-%m-%d")
# 获取当前月份的第一天
begin_month = math.ceil((datetime.now() - timedelta(days=1)).month / 3 - 1) * 3 + 1
begintime = f"{now.year}-{str(begin_month).rjust(2, '0')}-01"  # 赛季
# 获取当前月份的最后一天
# endtime = now.replace(day=calendar.monthrange(now.year, now.month)[1]).strftime(
#     "%Y-%m-%d"10
# )  # "2024-09-30"
begintime = now.strftime("%Y-%m-01") # 月绩效
endtime = lastday

print(f"{quarter}: {begintime} ~ {endtime}")


workdays: int = get_workdays(begintime, endtime)
print(f"截止{today}的工作日天数为: {workdays}天")
total_working_saturdays = count_working_saturdays(begintime, endtime)
print(f"截止{today}的大周工作日天数为: {total_working_saturdays}天")


def save_ranking_info(rank_users: List[User]):
    """保存排名信息"""
    print("*" * 120)
    print("*" * 120)
    filename = f"./logs/{today}.csv"
    with open(filename, "w+", encoding="utf-8") as f:
        print(f"大禹{quarter}工时排名：{begintime} ~ {endtime}")
        header = "排名,工号,姓名,应填工时(钉钉),实填工时(Jira),填报率,需求吞吐率,平均工时,开始时间,结束时间,工作日\n"
        f.write(header)
        for index, user in enumerate(rank_users, start=1):
            rank = index
            name = user.name
            # if user.work_hour_avg <= 8:
            #     name += "*"
            text: str = (
                f"{rank},{user.id},{name},{user.work_hour_require},{user.work_hour_real},{user.work_hour_per},"
                + f"{user.requirementThroughputRate},{user.work_hour_avg},{begintime},{endtime},{workdays}\n"
            )
            f.write(text)
            print(f"{str(rank).rjust(3, '0')}" + str(user))

    print(f"\nsave {filename} over")


async def get_user_list():
    """获取所有用户的项目填报工时"""
    metric = "teamViewEmployeeList"

    result = await Dayu.get_user_metric(deptId, metric, begintime, endtime)
    if not result:
        return []
    user_list: list[User] = []
    for item in pydash.get(result, "data.list", []):
        if "测试" in item["name"] or item["id"] == 777777:
            continue
        user = User(item["name"], item["id"])
        user.requirementThroughputRate = item["requirementThroughputRate"]
        if "-" not in user.requirementThroughputRate:
            user.requirementThroughputRate = (
                f"{float(user.requirementThroughputRate) * 100:.2f}%"
            )

        # if user.id != '195666':
        #     continue

        # 获取用户个人的填写工时
        # user_data = await Dayu.get_user_work_hours(deptId, user.id, quarter)
        # if not user_data:
        #     print(f"{user.id}/{user.name} get_user_work_hours faild. ")
        #     continue

        # # 交付成本
        # drillDownCalculateResult = await Dayu.drillDownCalculate(
        #     user.id,
        #     deptId,
        #     quarter,
        # )
        # # 实填工时=分子
        # moleculeVal = pydash.get(drillDownCalculateResult, "data.moleculeVal", 0)
        # user.work_hour_real = round(number=float(moleculeVal), ndigits=2)
        # # 应填工时=分母
        # denominatorVal = pydash.get(drillDownCalculateResult, "data.denominatorVal", 0)
        # user.work_hour_require = round(number=float(denominatorVal), ndigits=2)

        # 实填工时
        user_data = await Dayu.drillDownMapList(
            deptId,
            user.id,
            quarter,
            begintime,
            endtime,
            drillDownType="molecule",
        )
        if not user_data or not user_data["data"]:
            print(f"{user.id}/{user.name} get_user_work_hours faild. ")
            continue
        user.work_hour_real = round(
            number=float(pydash.get(user_data, "data.list[0].工时", 0)),
            ndigits=2,
        )

        # 应填工时
        user_data = await Dayu.drillDownMapList(
            deptId,
            user.id,
            quarter,
            begintime,
            endtime,
            drillDownType="denominator",
        )
        user.work_hour_require = round(
            number=float(pydash.get(user_data, "data.list[0].工时", 0)),
            ndigits=2,
        )

        # 平均工时
        # user.work_hour_avg = round(
        #     number=float(user.work_hour_require / workdays), ndigits=2
        # )
        user.work_hour_avg = 0
        except_work_hour_require = user.work_hour_require - total_working_saturdays * 8
        if except_work_hour_require > 0:
            user.work_hour_avg = round(
                number=float(except_work_hour_require / workdays), ndigits=2
            )
        print(f"[{user.id}]{user.name}: {user.work_hour_real}/{user.work_hour_require}")
        if user.work_hour_require <= 0:
            continue

        # 工时填报率=实填工时/应填工时；
        user_list.append(user)

        # print(user)
        # time.sleep(0.1)

    return user_list


async def main():
    USER_NAME = get_config("USER_NAME")
    PASSWORD = base64.b64decode(get_config("PASSWORD")).decode("utf-8")
    if not PASSWORD or not USER_NAME:
        return None

    await Dayu.login(USER_NAME, PASSWORD)
    user_list: list[User] = await get_user_list()
    if len(user_list) == 0:
        return
    # 排序
    rank_users = sorted(
        user_list, key=lambda user: user.work_hour_require, reverse=True
    )
    # 大禹工时排名：打印排序后的用户列表，包含排名
    save_ranking_info(rank_users)


if __name__ == "__main__":
    asyncio.run(main())
